package com.mcj.managementSystem.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mcj.managementSystem.common.Result;
import com.mcj.managementSystem.entity.Files;
import com.mcj.managementSystem.service.IFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件上传相关接口
 */
@RestController
@RequestMapping("/file")
public class FileController {

	@Value("${files.upload.path}")
	private String filesUploadPath;
	
	@Resource
	private IFileService fileService;
	
	private static final String prePath = "http://localhost:8081/file/";
	
	@PostMapping("/upload")
	public String upload(@RequestParam MultipartFile file) throws IOException {
		String originalFilename = file.getOriginalFilename();
		String type = FileUtil.extName(originalFilename);
		long size = file.getSize();
		
		
		// 定义一个文件的唯一标识码
		String uuid = IdUtil.fastSimpleUUID();
		String fileUUID =  uuid + StrUtil.DOT + type;
		File uploadFile = new File(filesUploadPath + fileUUID);
		
		// 存储目录文件夹如果不存在就新建 父目录
		File parentFile = uploadFile.getParentFile();
		if(!parentFile.exists()) {
			boolean mkdirs = parentFile.mkdirs();
		}
		
		String url;
		// 获取文件的md5
		String md5 = SecureUtil.md5(file.getInputStream());
		// 从数据库查询是否存在相同的记录
		Files dbFiles = getFileByMd5(md5);
		if (dbFiles != null) { 				// 文件已存在
			url = dbFiles.getUrl();
		} else {
			// 上传文件到磁盘
			file.transferTo(uploadFile);
			// 数据库若不存在重复文件，则不删除刚才上传的文件
			url = "http://localhost:8081/file/" + fileUUID;
		}
		
		// 存储数据库
		Files savaFile = new Files();
		savaFile.setName(originalFilename);
		savaFile.setType(type);
		savaFile.setSize(size / 1024);
		savaFile.setUrl(url);
		savaFile.setMd5(md5);
		fileService.save(savaFile);
		
		// 返回下载链接
		return url;
	}
	
	@GetMapping("/{fileUUID}")
	public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
		// 根据文件的唯一标识码获取文件
		File uploadFile = new File(filesUploadPath + fileUUID);
		// 设置输出流的格式
		ServletOutputStream os = response.getOutputStream();
		response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
		response.setContentType("application/octet-stream");
		// 读取文件的字节流
		os.write(FileUtil.readBytes(uploadFile));
		os.flush();
		os.close();
	}
	
	private Files getFileByMd5(String md5) {
		// 查询文件的md5是否存在
		QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("md5", md5);
		List<Files> filesList = fileService.list(queryWrapper);
		return filesList.size() == 0 ? null : filesList.get(0);
	}
	
	@PostMapping("/update")
	public Result update(@RequestBody Files files) {
		return Result.success(fileService.updateById(files));
	}
	
	@DeleteMapping("/{id}")
	public Result delete(@PathVariable Integer id) {
		Files files = fileService.getById(id);
		files.setIsDelete(true);
		fileService.updateById(files);
		return Result.success();
	}
	
	@PostMapping("/del/batch")
	public Result deleteBatch(@RequestBody List<Integer> ids) {
		// select * from sys_file where id in (id,id,id...)
		QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("id", ids);
		List<Files> files = fileService.list(queryWrapper);
		for (Files file : files) {
			file.setIsDelete(true);
			fileService.updateById(file);
		}
		return Result.success();
	}
	
	@GetMapping("/page")
	public Result findPage(@RequestParam Integer pageNum,
						   @RequestParam Integer pageSize,
						   @RequestParam(required = false) String name) {
		
		QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
		// 查询未删除的记录
		queryWrapper.eq("is_delete", false);
		if (StringUtils.hasText(name)) {
			queryWrapper.like("name", name);
		}
		return Result.success(fileService.page(new Page<>(pageNum, pageSize), queryWrapper));
	}
}

